<template>
  <div class="job-fair-list-page">
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">招聘会</h1>
        <p class="page-subtitle">发现更多线下招聘机会，直接面对面交流</p>
      </div>
    </div>

    <div class="container main-content">
      
      <!-- 热门招聘会（仅在第一页时显示） -->
      <div class="featured-fairs" v-if="currentPage === 1 && featuredFairs.length > 0">
        <h2 class="section-title">热门招聘会</h2>
        <el-carousel :interval="5000" type="card" height="500px">
          <el-carousel-item v-for="fair in featuredFairs" :key="fair.id">
            <div class="featured-fair-card" @click="goToFairDetail(fair.id)">
              <div class="featured-fair-poster">
                <img :src="fair.poster" alt="招聘会海报">
                <div class="fair-type-badge" :class="{ 'online': fair.type === 1 }">
                  {{ fair.type === 1 ? '线上招聘会' : '线下招聘会' }}
                </div>
                <div class="fair-badge" :class="getStatusClass(fair.status)">
                  {{ getStatusText(fair.status) }}
                </div>
                <div class="poster-overlay"></div>
              </div>
              
              <div class="featured-fair-content">
                <h3 class="fair-title">{{ fair.title }}</h3>
                
                <div class="fair-meta">
                  <div class="meta-item">
                    <el-icon><clock /></el-icon>
                    <span>{{ fair.time }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><location /></el-icon>
                    <span>{{ fair.location }}</span>
                  </div>
                  <div class="meta-stats">
                    <div class="stat-item">
                      <el-icon><office-building /></el-icon>
                      <span>{{ fair.companyCount }}家企业</span>
                    </div>
                    <div class="stat-item">
                      <el-icon><user /></el-icon>
                      <span>{{ fair.attendeeCount }}人报名</span>
                    </div>
                  </div>
                </div>

                <div class="fair-tags">
                  <el-tag size="small" effect="plain" class="primary-tag">
                    {{ fair.type === 1 ? '线上招聘会' : '线下招聘会' }}
                  </el-tag>
                  <el-tag 
                    v-for="(tag, index) in fair.tags" 
                    :key="index" 
                    size="small"
                    effect="plain"
                  >{{ tag }}</el-tag>
                </div>
                
                <div class="featured-companies">
                  <div class="companies-title">参会企业</div>
                  <div class="companies-grid">
                    <div 
                      v-for="(company, index) in fair.companies.slice(0, 6)" 
                      :key="index" 
                      class="company-item"
                    >
                      <div class="company-logo">
                        <img v-if="company.logo" :src="company.logo" :alt="company.name">
                        <div class="logo-fallback" v-else>
                          {{ company.name.substring(0, 1) }}
                        </div>
                      </div>
                      <div class="company-name">{{ company.name }}</div>
                    </div>
                    <div v-if="fair.companies.length > 6" class="company-item more">
                      <div class="more-count">+{{ fair.companies.length - 6 }}</div>
                      <div class="more-text">家企业</div>
                    </div>
                  </div>
                </div>
                
                <div class="action-btns">
                  <el-button 
                    type="primary" 
                    size="large"
                    :icon="fair.type === 1 ? 'VideoCamera' : 'Position'"
                    :disabled="fair.isRegistered"
                    :type="fair.isRegistered ? 'success' : 'primary'"
                    @click.stop="handleRegister(fair)"
                  >
                    {{ getActionButtonText(fair.status, fair.isRegistered) }}
                  </el-button>
                  <el-button 
                    size="large"
                    :icon="ArrowRight"
                    @click.stop="goToFairDetail(fair.id)"
                  >查看详情</el-button>
                </div>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 所有招聘会列表 -->
      <div class="fairs-section">
        <h2 class="section-title">所有招聘会</h2>
        
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
          <el-skeleton :rows="3" animated />
        </div>
        
        <div v-else-if="jobFairs.length === 0" class="empty-container">
          <el-empty description="暂无招聘会信息" />
        </div>
        
        <div v-else class="fair-cards">
          <div 
            v-for="fair in jobFairs" 
            :key="fair.id" 
            class="fair-card"
            @click="goToFairDetail(fair.id)">
            <div class="fair-poster">
              <img :src="fair.poster" alt="招聘会海报">
              <div class="fair-badge" :class="getStatusClass(fair.status)">
                {{ getStatusText(fair.status) }}
              </div>
              <div class="fair-type-badge" :class="{ 'online': fair.type === 1 }">
                {{ fair.type === 1 ? '线上' : '线下' }}
              </div>
            </div>
            
            <div class="fair-content">
              <h3 class="fair-title">{{ fair.title }}</h3>
              
              <div class="fair-info">
                <div class="info-row">
                  <el-icon><clock /></el-icon>
                  <span>{{ fair.time }}</span>
                </div>
                <div class="info-row">
                  <el-icon><location /></el-icon>
                  <span>{{ fair.location }}</span>
                </div>
              </div>
              
            
              
              <div class="fair-stats">
                <div class="stat-item">
                  <div class="stat-value">{{ fair.companyCount }}</div>
                  <div class="stat-label">参会企业</div>
                </div>
                
                <div class="stat-item">
                  <div class="stat-value">{{ fair.attendeeCount }}</div>
                  <div class="stat-label">已报名</div>
                </div>
              </div>
              
              <div class="card-footer">
                <el-button 
                  type="primary" 
                  :disabled="fair.status === 2 || fair.status === 3 || fair.isRegistered"
                  :type="fair.isRegistered ? 'success' : 'primary'"
                  @click.stop="handleRegister(fair)"
                >
                  {{ getActionButtonText(fair.status, fair.isRegistered) }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container" v-if="totalFairs > pageSize">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalFairs"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Clock, Location, OfficeBuilding, User, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getJobFairs, 
  registerForJobFair, 
  registerCompanyForJobFair, 
  checkUserRegistered,
  checkCompanyRegistered
} from '@/api/jobfair'
import { getUserInfo } from '@/api/auth'
import { checkCompany } from '@/api/user'

const router = useRouter()
const route = useRoute()

// 筛选条件
const filters = reactive({
  fairType: 'all',
  status: 'all',
  industry: '',
  city: ''
})

// 行业选项
const industryOptions = [
  { value: 1, label: '互联网/IT' },
  { value: 2, label: '金融/银行/保险' },
  { value: 3, label: '教育/培训' },
  { value: 4, label: '医疗健康' },
  { value: 5, label: '制造业' },
  { value: 6, label: '房地产/建筑' },
  { value: 7, label: '汽车/交通运输' },
  { value: 8, label: '服务业' },
  { value: 9, label: '文化传媒' },
  { value: 10, label: '能源/化工' }
]

// 城市选项
const cityOptions = [
  { value: 'beijing', label: '北京' },
  { value: 'shanghai', label: '上海' },
  { value: 'guangzhou', label: '广州' },
  { value: 'shenzhen', label: '深圳' },
  { value: 'hangzhou', label: '杭州' },
  { value: 'chengdu', label: '成都' }
]

// 分页参数
const currentPage = ref(1)
const pageSize = ref(12)
const totalFairs = ref(0)

// 加载状态
const loading = ref(false)

// 热门招聘会
const featuredFairs = ref([])

// 所有招聘会
const jobFairs = ref([])

// 用户角色
const userRole = ref(null)
const companyId = ref(null) // 存储用户的公司ID

// 获取招聘会状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '即将举行'
    case 1:
      return '进行中'
    case 2:
      return '已结束'
    case 3:
      return '已取消'
    default:
      return ''
  }
}

// 获取状态对应的样式类
const getStatusClass = (status) => {
  switch (status) {
    case 0:
      return 'upcoming'
    case 1:
      return 'ongoing'
    case 2:
    case 3:
      return 'ended'
    default:
      return ''
  }
}

// 获取操作按钮文本
const getActionButtonText = (status, isRegistered) => {
  if (isRegistered) {
    return '已报名'
  }
  
  switch (status) {
    case 0:
      // 根据用户角色返回不同文本
      return (userRole.value === 1 || userRole.value === '1') ? '企业报名' : '预约参加'
    case 1:
      return '立即参加'
    case 2:
      return '查看回顾'
    case 3:
      return '已取消'
    default:
      return '查看详情'
  }
}

// 跳转到招聘会详情
const goToFairDetail = (id) => {
  router.push(`/job-fairs/${id}`)
}

// 格式化招聘会时间
const formatJobFairTime = (startTime, endTime) => {
  if (!startTime || !endTime) return ''
  
  const start = new Date(startTime)
  const end = new Date(endTime)
  
  const startMonth = start.getMonth() + 1
  const startDay = start.getDate()
  const startHour = start.getHours().toString().padStart(2, '0')
  const startMinute = start.getMinutes().toString().padStart(2, '0')
  
  const endMonth = end.getMonth() + 1
  const endDay = end.getDate()
  const endHour = end.getHours().toString().padStart(2, '0')
  const endMinute = end.getMinutes().toString().padStart(2, '0')
  
  // 如果同一天，只显示一次日期
  if (startMonth === endMonth && startDay === endDay) {
    return `${start.getFullYear()}-${startMonth}-${startDay} ${startHour}:${startMinute}-${endHour}:${endMinute}`
  }
  
  return `${start.getFullYear()}-${startMonth}-${startDay} ${startHour}:${startMinute} 至 ${end.getFullYear()}-${endMonth}-${endDay} ${endHour}:${endMinute}`
}

// 处理注册/参加招聘会
const handleRegister = async (fair) => {
  // 阻止事件冒泡到卡片点击
  event.stopPropagation()
  
  // 添加日志打印
  console.log('招聘会列表 - 当前用户角色:', userRole.value, '类型:', typeof userRole.value)
  console.log('招聘会列表 - 是否招聘者:', userRole.value === 1 || userRole.value === '1')
  console.log('招聘会列表 - 当前招聘会状态:', fair.status)
  
  // 如果用户已报名，直接跳转到详情页
  if (fair.isRegistered) {
    ElMessage({
      message: '您已成功报名此招聘会',
      type: 'success',
      duration: 3000
    })
    goToFairDetail(fair.id)
    return
  }
  
  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessageBox.confirm(
      '您需要登录后才能报名参加招聘会，是否立即登录？',
      '提示',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      router.push({
        path: '/auth/login',
        query: { redirect: `/job-fairs/${fair.id}` }
      })
    }).catch(() => {})
    return
  }
  
  // 已结束或已取消的招聘会
  if (fair.status === 2 || fair.status === 3) {
    goToFairDetail(fair.id)
    return
  }
  
  // 进行中的招聘会
  if (fair.status === 1) {
    if (fair.type === 1) {
      // 线上招聘会直接进入
      router.push(`/job-fairs/${fair.id}/live`)
    } else {
      // 线下招聘会查看详情
      goToFairDetail(fair.id)
    }
    return
  }
  
  // 判断用户角色
  const isRecruiter = userRole.value === 1 || userRole.value === '1'
  console.log('招聘会列表 - 即将执行报名流程', '用户角色:', isRecruiter ? '招聘者' : '普通用户')
  
  // 根据角色执行不同的报名流程
  if (isRecruiter) {
    // 招聘者角色 - 执行企业报名流程
    try {
      console.log('招聘会列表 - 开始执行招聘者企业报名流程')
      
      // 调用专门的API来检查公司信息状态
      const companyCheckResponse = await checkCompany()
      console.log('招聘会列表 - 公司信息检查结果:', companyCheckResponse)
      
      // 如果API明确返回需要完善公司信息
      if (companyCheckResponse.data && companyCheckResponse.data.needCompany === true) {
        ElMessage.warning('请先完善公司信息后再进行报名')
        router.push('/recruiter/dashboard')
        return
      }
      
      // 获取公司ID - 可能在不同的地方
      let companyIdToUse = null
      
      // 从不同来源尝试获取公司ID
      const userResponse = await getUserInfo()
      const userInfo = userResponse.data
      console.log('招聘会列表 - 获取到的用户信息:', userInfo)
      
      if (userInfo.companyId) {
        companyIdToUse = userInfo.companyId
      } else if (companyCheckResponse.data && companyCheckResponse.data.companyId) {
        companyIdToUse = companyCheckResponse.data.companyId
      } else if (userInfo.company && userInfo.company.id) {
        companyIdToUse = userInfo.company.id
      }
      
      // 如果仍然没有公司ID，提示错误
      if (!companyIdToUse) {
        console.error('招聘会列表 - 找不到有效的公司ID:', {
          userInfoCompanyId: userInfo.companyId,
          checkResponseCompanyId: companyCheckResponse.data?.companyId,
          companyObjectId: userInfo.company?.id
        })
        ElMessage.warning('系统无法识别您的公司信息，请联系管理员')
        return
      }
      
      console.log('招聘会列表 - 准备使用的企业ID:', companyIdToUse)
      
      // 确认企业报名
      await ElMessageBox.confirm(
        `您确定要为企业报名"${fair.title}"吗？报名后，贵公司当前发布的所有招聘职位将会显示在招聘会中。`,
        '企业报名确认',
        {
          confirmButtonText: '确定报名',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
      
      console.log('招聘会列表 - 用户确认企业报名，准备调用API', {
        fairId: fair.id,
        companyId: companyIdToUse
      })
      
      // 调用企业报名API
      const response = await registerCompanyForJobFair(fair.id, companyIdToUse)
      console.log('招聘会列表 - 企业报名API响应:', response)
      
      if (response && response.data) {
        ElMessage.success('企业报名成功！贵公司的招聘职位已添加到招聘会中')
        // 更新报名状态并标记此招聘会为已报名
        fair.isRegistered = true
        fetchJobFairs()
      }
    } catch (error) {
      if (error === 'cancel') {
        console.log('招聘会列表 - 用户取消了企业报名操作')
        return; // 用户取消操作
      }
      
      console.error('招聘会列表 - 企业报名失败', error)
      
      // 尝试提取详细错误消息
      let errorMsg = '请稍后重试'
      if (error.response && error.response.data) {
        if (error.response.data.message) {
          errorMsg = error.response.data.message
        } else if (error.response.data.msg) {
          errorMsg = error.response.data.msg
        }
      } else if (error.message) {
        errorMsg = error.message
      }
      
      console.log('招聘会列表 - 企业报名错误消息:', errorMsg)
      
      // 如果是已报名的错误，给用户友好提示
      if (errorMsg.includes('已报名') || errorMsg.includes('重复报名')) {
        ElMessage({
          message: '贵公司已成功报名此招聘会，无需重复报名',
          type: 'warning',
          duration: 3000
        })
        // 标记此招聘会为已报名
        fair.isRegistered = true
        // 刷新数据以获取最新状态
        fetchJobFairs()
      } else {
        ElMessage.error('企业报名失败，' + errorMsg)
      }
    }
  } else {
    // 普通用户 - 执行普通报名流程
    ElMessageBox.confirm(
      `您确定要预约参加"${fair.title}"吗？`,
      '预约确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    ).then(async () => {
      try {
        console.log('招聘会列表 - 开始执行普通用户报名流程')
        const response = await registerForJobFair(fair.id)
        console.log('招聘会列表 - 普通用户报名API响应:', response)
        
        if (response && response.data) {
          ElMessage.success('预约成功！我们会在招聘会开始前给您发送提醒')
          // 更新报名人数并标记此招聘会为已报名
          fair.isRegistered = true
          fetchJobFairs()
        }
      } catch (error) {
        console.error('招聘会列表 - 普通用户报名失败', error)
        
        // 尝试提取详细错误消息
        let errorMsg = '请稍后重试'
        if (error.response && error.response.data) {
          if (error.response.data.message) {
            errorMsg = error.response.data.message
          } else if (error.response.data.msg) {
            errorMsg = error.response.data.msg
          }
        } else if (error.message) {
          errorMsg = error.message
        }
        
        console.log('招聘会列表 - 普通用户报名错误消息:', errorMsg)
        
        // 如果是已报名的错误，给用户友好提示
        if (errorMsg.includes('已报名') || errorMsg.includes('重复报名')) {
          ElMessage({
            message: '您已成功报名此招聘会，无需重复报名',
            type: 'warning',
            duration: 3000
          })
          // 标记此招聘会为已报名
          fair.isRegistered = true
          // 刷新数据以获取最新状态
          fetchJobFairs()
        } else {
          ElMessage.error('报名失败，' + errorMsg)
        }
      }
    }).catch(() => {
      console.log('招聘会列表 - 用户取消了普通报名操作')
    })
  }
}

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1
  fetchJobFairs()
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchJobFairs()
}

// 将行业ID转换为标签
const getIndustryTags = (industries) => {
  if (!industries) return []
  
  const tags = []
  // 确保industries是字符串类型
  if (typeof industries !== 'string') {
    console.warn('行业数据格式不正确', industries)
    return []
  }
  
  try {
    const industryIds = industries.split(',').map(id => parseInt(id.trim()))
    
    for (const id of industryIds) {
      const industry = industryOptions.find(item => item.value === id)
      if (industry) {
        tags.push(industry.label)
      }
    }
  } catch (error) {
    console.error('解析行业数据失败', error)
    return []
  }
  
  return tags
}

// 获取招聘会列表
const fetchJobFairs = async () => {
  loading.value = true;
  
  try {
    // 先获取用户信息（如果已登录）
    const token = localStorage.getItem('token');
    if (token) {
      try {
        console.log('招聘会列表 - 刷新招聘会前获取用户信息');
        
        const userResponse = await getUserInfo();
        if (userResponse && userResponse.data) {
          userRole.value = userResponse.data.role;
          console.log('招聘会列表 - 获取到用户角色:', userRole.value, '类型:', typeof userRole.value);
          
          // 保存公司ID，如果存在
          if (userResponse.data.companyId) {
            companyId.value = userResponse.data.companyId;
            console.log('招聘会列表 - 获取到企业ID:', companyId.value);
          } else if (userResponse.data.company && userResponse.data.company.id) {
            companyId.value = userResponse.data.company.id;
            console.log('招聘会列表 - 从company对象获取到企业ID:', companyId.value);
          }
        }
      } catch (error) {
        console.error('招聘会列表 - 获取用户信息失败:', error);
      }
    }
    
    // 构建查询参数
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 添加筛选条件
    if (filters.fairType !== 'all') {
      params.type = filters.fairType === 'online' ? 1 : 0
    }
    
    if (filters.status !== 'all') {
      params.status = filters.status === 'upcoming' ? 0 : 
                     filters.status === 'ongoing' ? 1 : 
                     filters.status === 'ended' ? 2 : null
    }
    
    if (filters.industry) {
      params.industry = filters.industry
    }
    
    if (filters.city) {
      params.city = filters.city
    }
    
    // 调用API获取数据
    const response = await getJobFairs(params)
    
    if (response && response.data) {
      // 处理响应数据
      const { records, total } = response.data
      
      // 设置总数
      totalFairs.value = total || 0
      
      // 转换为展示格式
      const processedFairs = records.map(fair => {
        // 暂时不获取企业列表，因为API不可用
        const companies = []
        
        // 处理行业标签
        const tags = getIndustryTags(fair.industries)
        
        return {
          id: fair.id,
          title: fair.title,
          time: formatJobFairTime(fair.startTime, fair.endTime),
          location: fair.location,
          type: fair.type,
          poster: fair.poster || 'https://img.yzcdn.cn/vant/cat.jpeg', // 默认海报
          status: fair.status,
          companyCount: fair.registeredCompanies || 0,
          jobCount: fair.registeredJobs || 0,
          attendeeCount: fair.registeredUsers || 0,
          tags,
          companies,
          description: fair.description,
          address: fair.address,
          isRegistered: false // 默认未报名
        }
      })
      
      // 更新招聘会列表
      jobFairs.value = processedFairs
      
      // 选择前2个作为特色招聘会
      if (currentPage.value === 1 && processedFairs.length > 0) {
        featuredFairs.value = processedFairs.slice(0, Math.min(2, processedFairs.length))
      } else {
        featuredFairs.value = []
      }
      
      // 获取用户登录状态
      if (token && processedFairs.length > 0) {
        // 检查用户是否已报名各招聘会
        await checkRegistrationStatus(processedFairs)
      }
    } else {
      jobFairs.value = []
      featuredFairs.value = []
      totalFairs.value = 0
    }
  } catch (error) {
    console.error('获取招聘会列表失败', error)
    ElMessage.error('获取招聘会列表失败，请稍后重试')
    jobFairs.value = []
    featuredFairs.value = []
    totalFairs.value = 0
  } finally {
    loading.value = false
  }
}

// 检查用户是否已报名招聘会
const checkRegistrationStatus = async (fairs) => {
  try {
    // 获取用户角色判断
    const isRecruiter = userRole.value === 1 || userRole.value === '1';
    console.log('招聘会列表 - 报名状态检查 - 用户角色:', userRole.value, '是否为招聘者:', isRecruiter);
    
    // 根据用户角色选择不同的检查方法
    if (isRecruiter && companyId.value) {
      await checkCompanyRegistrationStatus(fairs, companyId.value);
    } else {
      await checkUserRegistrationStatus(fairs);
    }
  } catch (error) {
    console.error('招聘会列表 - 检查报名状态失败', error);
  }
}

// 检查企业报名状态
const checkCompanyRegistrationStatus = async (fairs, companyIdToUse) => {
  try {
    console.log('招聘会列表 - 开始检查企业报名状态, 企业ID:', companyIdToUse);
    
    // 使用Promise.all并行请求所有招聘会的报名状态
    const checkPromises = fairs.map(fair => {
      console.log(`招聘会列表 - 检查企业报名状态 - 招聘会ID:${fair.id}, 企业ID:${companyIdToUse}`);
      return checkCompanyRegistered(fair.id, companyIdToUse)
        .then(response => {
          if (response && response.data !== undefined) {
            console.log(`招聘会列表 - 企业报名状态结果 - 招聘会ID:${fair.id}`, response.data);
            // 如果返回true，表示企业已报名
            fair.isRegistered = response.data;
            
            // 同步更新featuredFairs中对应的招聘会状态
            const featuredFair = featuredFairs.value.find(f => f.id === fair.id);
            if (featuredFair) {
              featuredFair.isRegistered = response.data;
            }
          }
          return fair;
        })
        .catch(error => {
          console.error(`招聘会列表 - 检查企业报名状态失败 - 招聘会ID:${fair.id}`, error);
          return fair;
        });
    });
    
    await Promise.all(checkPromises);
  } catch (error) {
    console.error('招聘会列表 - 检查企业报名状态失败', error);
  }
}

// 检查普通用户报名状态
const checkUserRegistrationStatus = async (fairs) => {
  try {
    console.log('招聘会列表 - 开始检查普通用户报名状态');
    
    // 使用Promise.all并行请求所有招聘会的报名状态
    const checkPromises = fairs.map(fair => {
      return checkUserRegistered(fair.id)
        .then(response => {
          if (response && response.data !== undefined) {
            console.log(`招聘会列表 - 用户报名状态结果 - 招聘会ID:${fair.id}`, response.data);
            // 如果返回true，表示用户已报名
            fair.isRegistered = response.data;
            
            // 同步更新featuredFairs中对应的招聘会状态
            const featuredFair = featuredFairs.value.find(f => f.id === fair.id);
            if (featuredFair) {
              featuredFair.isRegistered = response.data;
            }
          }
          return fair;
        })
        .catch(error => {
          console.error(`招聘会列表 - 检查用户报名状态失败 - 招聘会ID:${fair.id}`, error);
          return fair;
        });
    });
    
    await Promise.all(checkPromises);
  } catch (error) {
    console.error('招聘会列表 - 检查普通用户报名状态失败', error);
  }
}

// 监听路由变化
watch(() => route.path, (newPath, oldPath) => {
  console.log('招聘会列表 - 检测到路由变化:', oldPath, '->', newPath);
  
  // 当用户从其他页面导航到招聘会列表页
  if (newPath.includes('/job-fairs') && !newPath.includes('/job-fairs/')) {
    console.log('招聘会列表 - 用户返回招聘会列表页，重新获取数据');
    
    // 重新获取招聘会列表数据，包括报名状态
    fetchJobFairs();
  }
}, { immediate: true });

// 在onMounted中获取用户角色
onMounted(() => {
  console.log('招聘会列表 - 组件挂载，准备获取数据')
  fetchJobFairs()
  
  // 获取用户角色信息
  const token = localStorage.getItem('token')
  if (token) {
    console.log('招聘会列表 - 用户已登录，准备获取用户角色')
    
    getUserInfo().then(response => {
      if (response && response.data) {
        userRole.value = response.data.role
        console.log('招聘会列表 - 获取到用户角色:', userRole.value, '类型:', typeof userRole.value)
        console.log('招聘会列表 - 用户详细信息:', response.data)
        
        // 保存公司ID，如果存在
        if (response.data.companyId) {
          companyId.value = response.data.companyId
          console.log('招聘会列表 - 获取到企业ID:', companyId.value)
        } else if (response.data.company && response.data.company.id) {
          companyId.value = response.data.company.id
          console.log('招聘会列表 - 从company对象获取到企业ID:', companyId.value)
        }
      } else {
        console.warn('招聘会列表 - 获取用户信息失败: 响应数据为空')
      }
    }).catch(error => {
      console.error('招聘会列表 - 获取用户角色失败:', error)
    })
  } else {
    console.log('招聘会列表 - 用户未登录，跳过获取用户角色')
  }
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

/* 追加CSS变量 */
:root {
  --color-light: #f0f2f5;
  --color-primary-light: #ecf5ff;
}

/* 多行文本省略函数 */
.multi-line-ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.job-fair-list-page {
  min-height: calc(100vh - 240px);
}

.page-header {
  background: linear-gradient(135deg, #4a71ba, #7c32a1);
  padding: var(--spacing-xl) 0;
  color: white;
  margin-bottom: var(--spacing-xl);
  
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 var(--spacing-lg);
  }
  
  .page-title {
    font-size: 2rem;
    font-weight: 700;
    margin: 0 0 var(--spacing-xs);
  }
  
  .page-subtitle {
    font-size: 1.1rem;
    opacity: 0.9;
  }
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-lg);
}

.main-content {
  margin-bottom: var(--spacing-xxl);
}

.filter-section {
  background: white;
  border-radius: var(--border-radius);
  padding: var(--spacing-lg);
  margin-bottom: var(--spacing-xl);
  box-shadow: var(--box-shadow-sm);
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-md);
  
  .filter-item {
    display: flex;
    align-items: center;
    margin-right: var(--spacing-lg);
    margin-bottom: var(--spacing-sm);
    
    .filter-label {
      margin-right: var(--spacing-xs);
      white-space: nowrap;
      color: var(--text-secondary);
    }
  }
}

.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: var(--spacing-lg);
  color: var(--text-primary);
}

/* 特色招聘会 */
.featured-fairs {
  margin-bottom: var(--spacing-xxl);
  
  :deep(.el-carousel__item) {
    overflow: visible;
    
    &.is-active {
      .featured-fair-card {
        transform: scale(1);
        opacity: 1;
      }
    }
    
    &:not(.is-active) {
      .featured-fair-card {
        transform: scale(0.9);
        opacity: 0.6;
      }
    }
  }
  
  :deep(.el-carousel__arrow) {
    width: 48px;
    height: 48px;
    background-color: rgba(255, 255, 255, 0.9);
    border: 1px solid #e4e7ed;
    color: var(--color-primary);
    font-size: 24px;
    z-index: 100;
    
    &:hover {
      background-color: white;
    }
  }
  
  .featured-fair-card {
    height: 100%;
    background: white;
    border-radius: var(--border-radius-lg);
    overflow: hidden;
    box-shadow: var(--box-shadow-lg);
    display: grid;
    grid-template-columns: 45% 55%;
    cursor: pointer;
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    
    .featured-fair-poster {
      position: relative;
      overflow: hidden;
      height: 100%;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
      }
      
      .poster-overlay {
        position: absolute;
        inset: 0;
        background: linear-gradient(
          to right,
          rgba(0, 0, 0, 0.4),
          rgba(0, 0, 0, 0.1)
        );
      }
      
      .fair-type-badge {
        position: absolute;
        top: var(--spacing-md);
        left: var(--spacing-md);
        padding: 6px 12px;
        border-radius: var(--border-radius);
        font-size: 0.9rem;
        font-weight: 500;
        color: white;
        background-color: rgba(230, 162, 60, 0.9);
        backdrop-filter: blur(4px);
        z-index: 1;
        
        &.online {
          background-color: rgba(64, 158, 255, 0.9);
        }
      }
      
      .fair-badge {
        position: absolute;
        top: var(--spacing-md);
        right: var(--spacing-md);
        padding: 6px 12px;
        border-radius: var(--border-radius);
        font-size: 0.9rem;
        font-weight: 500;
        color: white;
        backdrop-filter: blur(4px);
        z-index: 1;
        
        &.upcoming {
          background-color: rgba(103, 194, 58, 0.9);
        }
        
        &.ongoing {
          background-color: rgba(230, 162, 60, 0.9);
        }
        
        &.ended {
          background-color: rgba(144, 147, 153, 0.9);
        }
      }
    }
    
    &:hover {
      .featured-fair-poster img {
        transform: scale(1.05);
      }
    }
    
    .featured-fair-content {
      padding: var(--spacing-xl);
      display: flex;
      flex-direction: column;
      gap: var(--spacing-md);
      overflow: hidden;
      background: white;
      
      .fair-title {
        font-size: 1.6rem;
        font-weight: 600;
        line-height: 1.3;
        color: var(--text-primary);
        margin: 0;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .fair-meta {
        display: flex;
        flex-direction: column;
        gap: var(--spacing-sm);
        
        .meta-item {
          display: flex;
          align-items: center;
          gap: var(--spacing-sm);
          color: var(--text-secondary);
          font-size: 1rem;
          
          .el-icon {
            font-size: 1.2rem;
            color: var(--color-primary);
          }
        }
        
        .meta-stats {
          display: flex;
          gap: var(--spacing-lg);
          margin-top: var(--spacing-sm);
          
          .stat-item {
            display: flex;
            align-items: center;
            gap: var(--spacing-xs);
            color: var(--color-primary);
            font-weight: 500;
            
            .el-icon {
              font-size: 1.1rem;
            }
          }
        }
      }
      
      .fair-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .el-tag {
          padding: 0 12px;
          height: 28px;
          font-size: 0.9rem;
          border-radius: var(--border-radius);
          
          &.primary-tag {
            color: var(--color-primary);
            border-color: var(--color-primary);
            background-color: var(--color-primary-light);
          }
        }
      }
      
      .featured-companies {
        .companies-title {
          font-size: 1rem;
          font-weight: 500;
          color: var(--text-primary);
          margin-bottom: var(--spacing-sm);
        }
        
        .companies-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
          gap: var(--spacing-sm);
          
          .company-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 6px;
            padding: var(--spacing-xs);
            border-radius: var(--border-radius);
            background-color: var(--color-light);
            transition: all 0.3s;
            
            &:hover {
              background-color: var(--color-primary-light);
            }
            
            .company-logo {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              overflow: hidden;
              background-color: white;
              display: flex;
              align-items: center;
              justify-content: center;
              
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
              
              .logo-fallback {
                width: 100%;
                height: 100%;
                background-color: var(--color-primary);
                color: white;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: 600;
                font-size: 1.1rem;
              }
            }
            
            .company-name {
              font-size: 0.85rem;
              color: var(--text-secondary);
              text-align: center;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }
            
            &.more {
              background-color: var(--color-primary-light);
              justify-content: center;
              cursor: pointer;
              
              .more-count {
                font-size: 1.1rem;
                font-weight: 600;
                color: var(--color-primary);
              }
              
              .more-text {
                font-size: 0.85rem;
                color: var(--color-primary);
              }
            }
          }
        }
      }
      
      .action-btns {
        margin-top: auto;
        display: flex;
        gap: var(--spacing-md);
        
        .el-button {
          flex: 1;
          padding: var(--spacing-sm) var(--spacing-lg);
          font-size: 1rem;
          
          .el-icon {
            font-size: 1.1rem;
          }
        }
      }
    }
  }
}

/* 招聘会列表 */
.fairs-section {
  .loading-container,
  .empty-container {
    min-height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .fair-cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: var(--spacing-lg);
    
    .fair-card {
      background: white;
      border-radius: var(--border-radius);
      overflow: hidden;
      box-shadow: var(--box-shadow-sm);
      transition: all 0.3s;
      cursor: pointer;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: var(--box-shadow-md);
      }
      
      .fair-poster {
        height: 180px;
        position: relative;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .fair-badge {
          position: absolute;
          top: var(--spacing-sm);
          right: var(--spacing-sm);
          padding: 4px 8px;
          border-radius: var(--border-radius-sm);
          font-size: 0.8rem;
          color: white;
          background-color: rgba(0, 0, 0, 0.6);
          
          &.upcoming {
            background-color: rgba(103, 194, 58, 0.85);
          }
          
          &.ongoing {
            background-color: rgba(230, 162, 60, 0.85);
          }
          
          &.ended {
            background-color: rgba(144, 147, 153, 0.85);
          }
        }
        
        .fair-type-badge {
          position: absolute;
          top: var(--spacing-sm);
          left: var(--spacing-sm);
          padding: 4px 8px;
          border-radius: var(--border-radius-sm);
          font-size: 0.8rem;
          color: white;
          background-color: rgba(230, 162, 60, 0.85);
          
          &.online {
            background-color: rgba(64, 158, 255, 0.85);
          }
        }
      }
      
      .fair-content {
        padding: var(--spacing-md);
        
        .fair-title {
          font-size: 1.1rem;
          font-weight: 600;
          margin: 0 0 var(--spacing-sm);
          color: var(--text-primary);
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          height: 2.6em;
        }
        
        .fair-info {
          margin-bottom: var(--spacing-sm);
          
          .info-row {
            display: flex;
            align-items: center;
            margin-bottom: var(--spacing-xs);
            color: var(--text-secondary);
            font-size: 0.9rem;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            
            .el-icon {
              margin-right: var(--spacing-xs);
              color: var(--color-primary);
              flex-shrink: 0;
            }
            
            span {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
        
        .company-logos {
          margin-bottom: var(--spacing-sm);
          width: 100%;
          overflow: hidden;
          
          .logos-title {
            font-size: 0.9rem;
            color: var(--text-secondary);
            margin-bottom: var(--spacing-xs);
          }
          
          .logos-list {
            display: flex;
            align-items: center;
            flex-wrap: nowrap;
            gap: var(--spacing-xs);
            width: 100%;
            overflow: hidden;
            position: relative;
            
            .company-logo {
              width: 32px;
              height: 32px;
              min-width: 32px;
              border-radius: 50%;
              overflow: hidden;
              flex-shrink: 0;
              
              .logo-content {
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                
                img {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }
                
                .logo-fallback {
                  width: 100%;
                  height: 100%;
                  background-color: var(--color-primary);
                  color: white;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-weight: 700;
                  font-size: 0.8rem;
                }
              }
            }
            
            .more-companies {
              font-size: 0.8rem;
              color: var(--text-secondary);
              flex-shrink: 0;
              white-space: nowrap;
              background-color: #f0f2f5;
              border-radius: 12px;
              padding: 2px 8px;
            }
          }
        }
        
        .fair-stats {
          display: flex;
          justify-content: space-between;
          margin-bottom: var(--spacing-md);
          
          .stat-item {
            text-align: center;
            
            .stat-value {
              font-size: 1.1rem;
              font-weight: 600;
              color: var(--color-primary);
            }
            
            .stat-label {
              font-size: 0.8rem;
              color: var(--text-secondary);
            }
          }
        }
        
        .card-footer {
          .el-button {
            width: 100%;
          }
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: var(--spacing-xl);
    display: flex;
    justify-content: center;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .featured-fair-card {
    grid-template-columns: 40% 60% !important;
  }
}

@media (max-width: 992px) {
  .featured-fair-card {
    grid-template-columns: 1fr !important;
    grid-template-rows: 300px 1fr;
    
    .featured-fair-content {
      padding: var(--spacing-lg) !important;
      
      .fair-title {
        font-size: 1.4rem !important;
      }
      
      .companies-grid {
        grid-template-columns: repeat(auto-fill, minmax(80px, 1fr)) !important;
      }
    }
  }
}

@media (max-width: 768px) {
  :deep(.el-carousel__item) {
    width: 95% !important;
    
    &:not(.is-active) {
      .featured-fair-card {
        transform: scale(0.95);
      }
    }
  }
  
  .featured-fair-card {
    .featured-fair-content {
      padding: var(--spacing-md) !important;
      
      .fair-title {
        font-size: 1.2rem !important;
      }
      
      .fair-meta {
        .meta-stats {
          flex-direction: column;
          gap: var(--spacing-xs);
        }
      }
      
      .companies-grid {
        grid-template-columns: repeat(3, 1fr) !important;
      }
      
      .action-btns {
        flex-direction: column;
        
        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style> 
